package cn.ucuser.music.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

public class HttpClient {
    private final static String USERAGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.157 Safari/537.36";
    private final static String COOKIE = "os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true";
    private final static String REFERER = "http://music.163.com/";
    public static String getConnection(String url, Map<String, Object> data) throws Exception {
        String response = "";
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuffer parameterBuffer = new StringBuffer();
        URL curl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) curl.openConnection();
        if (data != null && data.size() > 0) {
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Referer", REFERER);
            conn.setRequestProperty("Cookie", COOKIE);
            conn.setRequestProperty("User-Agent", USERAGENT);

            Iterator iterator = data.keySet().iterator();
            String key = null;
            String value = null;

            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (data.get(key) != null) {
                    value = (String) data.get(key);
                } else {
                    value = "";
                }
                parameterBuffer.append(key).append("=")
                        .append(URLEncoder.encode(value, "utf-8"));
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
            try {
                out = new OutputStreamWriter(conn.getOutputStream());
                out.write(parameterBuffer.toString());
                out.flush();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    response += lines;
                }
            } catch (Exception e) {

            } finally {
                reader.close();
                out.close();
            }
        }
        return response;
    }
}
